#include "ItemCreator.h"
#include "ellipseitem.h"
#include <gui\painting\qbrush.h>

namespace PackSim
{

	ItemCreator::ItemCreator(QGraphicsItem* parent)
	: QGraphicsRectItem(parent)
	{
		mColumNumber = 1;
		mColumnPitch = 30;
		mRowNumber = 4;
		mRowPitch = 30;

		mCreationPeriod = 5000;
		mTimeSinceCreated = 0;

		mItemRect =QRectF(-5,-10,10,20);
		mItemRotation = 0;
		mItemColor = QColor(Qt::gray);
		mItemList.clear();

		mColor = QColor(Qt::GlobalColor::darkGray);
		setColor(mColor);
		resizeCreator();

		QObject::connect(&mCreationTimer,SIGNAL(timeout()),this,SLOT(onCreationTimerTimeOut()) );
	}

	ItemCreator::~ItemCreator()
	{

	}

	void ItemCreator::startCreation()
	{
		//mCreationTimer.start(mCreationPeriod);
	}

	void ItemCreator::stopCreation()
	{
		//mCreationTimer.stop();
	}

	void ItemCreator::onCreationTimerTimeOut()
	{
		createItems();
	}

	int ItemCreator::columNumber() const
	{
		return mColumNumber;
	}

	void ItemCreator::setColumNumber( int columNumber )
	{
		mColumNumber = columNumber;
		resizeCreator();
	}

	int ItemCreator::columnPitch() const
	{
		return mColumnPitch;
	}

	void ItemCreator::setColumnPitch( int columnPitch )
	{
		mColumnPitch = columnPitch;
		resizeCreator();
	}

	int ItemCreator::rowNumber() const
	{
		return mRowNumber;
	}

	void ItemCreator::setRowNumber( int rowNumber )
	{
		mRowNumber =rowNumber;
		resizeCreator();
	}

	int ItemCreator::rowPitch() const
	{
		return mRowPitch;
	}

	void ItemCreator::setRowPitch( int rowPitch )
	{
		mRowPitch = rowPitch;
		resizeCreator();
	}

	void ItemCreator::resizeCreator()
	{
		qreal width = mColumNumber*mColumnPitch;
		qreal height = mRowNumber*mRowPitch;
		setRect(0,0,width,height);
	}

	void ItemCreator::setRect( const QRectF & rectangle )
	{
		QGraphicsRectItem::setRect(rectangle);
	}

	void ItemCreator::setRect( qreal x, qreal y, qreal width, qreal height )
	{
		QGraphicsRectItem::setRect(x,y,width,height);
	}


	QColor ItemCreator::color() const
	{
		return mColor;
	}

	void ItemCreator::setColor( QColor color )
	{
		mColor = color;
		mColor.setAlpha(200);
		QBrush brush(mColor);
		setBrush(brush);
	}

	void ItemCreator::createItems()
	{
		mTimeSinceCreated = 0;
		mItemList.clear();

		for(int i = 0; i< mColumNumber ; i++)
		{
			for(int y = 0; y< mRowNumber ; y++)
			{
				EllipseItem *itm = new EllipseItem(this);
				QPointF pos(i*mColumnPitch + mColumnPitch/2 , y*mRowPitch + mColumnPitch/2);

				itm->setPos(pos);
				itm->setRect(mItemRect);
				itm->setRotation(mItemRotation);
				itm->setColor(mItemColor);

				mItemList.append(itm);

			}

		}

		emit ItemCreatorSignalItemsCreated(this,mItemList);
	}

	void ItemCreator::update(int aDeltaTime)
	{
		mTimeSinceCreated += aDeltaTime;
		if(mTimeSinceCreated > mCreationPeriod)
		{	mTimeSinceCreated = 0;
			createItems();
		}
		
	}


}
